﻿
using System;
using Random = Hyt.Core.Utils.Random;

namespace Hyt.Web.Security
{
    /// <summary>
    /// Cookie方式验证码管理器
    /// </summary>
    public class CookieSafeCodeManager : AbstractSafeCodeProvider
    {
        public const string SafecodeValid = "_HYT_SVACDODCEDFILE";
        /// <summary>
        /// 根据SESSIONID获取SafeCode
        /// </summary>
        /// <param name="sessionid">SESSIONID</param>
        /// <returns></returns>
        public override string GetSafeCode( string sessionid )
        {
            if ( System.Web.HttpContext.Current == null ||
                System.Web.HttpContext.Current.Request.Cookies[SafecodeValid] == null ||
                System.Web.HttpContext.Current.Request.Cookies[SafecodeValid].Value == null)
            {
                return "";
            }

            string cookievalue = System.Web.HttpContext.Current.Request.Cookies[SafecodeValid].Value;
            var decodestr = Hyt.Core.Cryptography.DES.Decrypt(cookievalue);
            if (string.IsNullOrWhiteSpace(decodestr))
            {
                return "";
            }
            string[] arr = decodestr.Split(',');
            if (arr.Length != 2)
            {
                return "";
            }
            DateTime dt;
            if (!DateTime.TryParse(arr[1],out dt))
            {
                return "";
            }
            if (dt.AddMinutes(5) < DateTime.Now)
            {
                return "";
            }
            return arr[0];
        }

        /// <summary>
        /// 获取新验证码
        /// </summary>
        /// <param name="sessionid">SESSIONID</param>
        /// <returns></returns>
        public override string NewSafeCode( string sessionid )
        {
            string code = Random.GetRandomString( 4 );
            HttpHelper.WriteCookie(System.Web.HttpContext.Current, SafecodeValid, Hyt.Core.Cryptography.DES.Encrypt(code + "," + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));
            
            return code;
        }

        /// <summary>
        /// 清除验证码
        /// </summary>
        /// <param name="sessionid">SESSIONID</param>
        public override void ClearSafeCode( string sessionid )
        {
            HttpHelper.WriteCookie(System.Web.HttpContext.Current, SafecodeValid, "");
        }
    }
}